$(function () {
  var role_datagrid = $("#role_datagrid");
  var role_dialog = $("#role_dialog");
  var role_form =  $("#role_form");
  // 权限框
  let selfPermissions = $('#selfPermissions');
  let allPermissions = $('#allPermissions');
  // 树菜单
  var menu_combotree = $('#menu_combotree');

// 数据 表
  role_datagrid.datagrid({
    url: "/role/query.do",
    fitColumns: true, // 自适应列
    fit: true,
    striped: true,  // 斑马线
    pagination: true,
    rownumbers: true,
    pageSize: 10,
    pageNumber: 1,
    singleSelect: true, // 单选
    toolbar: "#role_toolbar",
    columns: [
      [
        {field: 'name', title: '角色名', width: 80},
        {field: 'sn', title: '角色编号', width: 80}
      ]
    ]
  });

  // 对话 框
  role_dialog.dialog({
    width: 500,
    height: 500,
    top: 100,
    buttons: "#form_btns",
    closed: true,
    onClose: function () {
      role_form.form("clear");
      // 清空权限
      selfPermissions.datagrid('loadData', []);
      // 重载 权限
      allPermissions.datagrid('reload')
      // 清空 菜单
    }
  });

  function openSetTitle(str) {
    role_dialog.dialog("setTitle", str)
    role_dialog.dialog("open")
  }

  // 权限框
  allPermissions.datagrid({
    url: '/permission/selectAll.do',
    title: '所有权限',
    width: 200,
    height: 300,
    fitColumns:true,
    columns:[[
      {field:'name', title: '权限名称', width: 80, align: 'center'}
    ]],
    onClickRow: function (index, row) {
      selfPermissions.datagrid('appendRow', row);
      allPermissions.datagrid('deleteRow', index);
    },
  })

  // 选择 树菜单
  menu_combotree.combotree({
    onCheck1: (function () {
      var select = function (node, checked) {
        var treeObj = menu_combotree.combotree('tree');
        var children = treeObj.tree('getChildren', node.target);
        children.forEach(item =>  treeObj.tree(checked ? 'check': 'uncheck', item.target))
      }
      return function (node,checked) {
        // 选中子类
        select(node, checked)
        // 勾选 父类
        if (!checked) return  // 不是 选中就 不用
        var treeObj = menu_combotree.combotree('tree');
        var parent = treeObj.tree('getParent', node.target);
        if (!parent) return // 没有父类 也 不用
        treeObj.tree('check', parent.target);
      }
    })(),
    onCheck: (function () {
      var getParent = function (treeObj,node) {
        var parent = treeObj.tree('getParent', node.target);
        return parent;
      }
      var getParentIds = function (treeObj, node,arr) {
        arr = arr || [];
        if (node.parent) {
          arr.push(node.parent.id.toString())
          return getParentIds(treeObj, getParent(treeObj, node), arr)
        }
        return arr;
      }
      var getChildIds = function (node, arr) {
        arr = arr || []
        if (!node.children) return arr
        node.children.forEach(item => {
          arr.push(item.id.toString())
          arr = getChildIds(item, arr)
        })
        return arr
      }
      return function (node,checked) {
        console.log(node.id);
        // 获取 树 对象
        var treeObj = menu_combotree.combotree('tree');
        var arr = menu_combotree.combotree('getValues');
        // 不是 选中
        if (!checked) {
          var childIds = getChildIds(node);
          arr = arr.filter(id => childIds.every(childId => childId != id))
          menu_combotree.combotree('setValues', arr);
          return
        }
        // 获取 原来 的 值
        // 回选 子数据
        var childIds = getChildIds(node);
        // 回选 父数据
        var parentIds = getParentIds(treeObj, node);
        console.log(parentIds);
        // 数组 去重
        arr = Array.from(new Set([...arr, ...parentIds, ...childIds]))
        // 设置 新数据
        menu_combotree.combotree('setValues', arr);
      }
    })()
  })




  selfPermissions.datagrid({
    url: '/permission/selectByRoleId.do',
    title: '已有权限',
    width: 200,
    height: 300,
    fitColumns:true,
    columns:[[
      {field:'name', title: '权限名称', width: 80, align: 'center'}
    ]],
    onClickRow: function (index, row) {
      allPermissions.datagrid('appendRow', row);
      selfPermissions.datagrid('deleteRow', index);
    },
    onLoadSuccess: function (data) {
      var ids = data.rows.map(item => item.id);
      var rows = allPermissions.datagrid('getRows');
      var resRows = rows.filter(item => ids.every(id => id != item.id));
      allPermissions.datagrid('loadData', {total: resRows.length, rows: resRows});
    }
  })


  var objMethod = {
    add : function () {
      openSetTitle("新增角色")
    },
    edit : function () {
      var row = role_datagrid.datagrid("getSelected");
      if (!row) {
        $.messager.alert("温馨提示", '请选择一条数据', 'warning')
        return
      }
      // 回选 菜单
      $.get('/menu/selectByRoleId.do', {id: row.id}, function (data) {
        menu_combotree.combotree('setValues', data)
      })
      // 回选 权限
      selfPermissions.datagrid('load', {id: row.id});
      // 回选 数据
      role_form.form("load", row)
      openSetTitle("编辑角色")
    },
    del: function () {
      var row = role_datagrid.datagrid("getSelected");
      if (!row) {
        $.messager.alert("温馨提示", '请选择一条数据', 'warning')
        return
      }
      $.messager.confirm('确认', '你确认要删除【'+ row.name+'】吗？', function (r) {
        if (!r) return
        $.get('/role/del.do', {id: row.id}, function (data) {
          if (data.success) {
            $.messager.alert("温馨提示", '操作成功', 'info', function () {
              role_datagrid.datagrid("reload");  // 刷新
            })
          } else {
            $.messager.alert("温馨提示", '操作失败', 'info', function () {
            })
          }
        })
      })
    },
    save : function () {
      // 提交表单
      role_form.form("submit", {
        url: "/role/saveOrUpdate.do",
        onSubmit: function (params) {
          var rows = selfPermissions.datagrid('getRows');
          rows.forEach((row, index) => params[`permissions[${index}].id`] = row.id)
          // 选中 menu
          var trees = menu_combotree.combotree('getValues');
          trees.forEach((id, index) => params[`menus[${index}].id`] = id)
          return role_form.form('validate')
        },
        success: function (data) {
          data = $.parseJSON(data)
          if (data.success) {
            $.messager.alert("温馨提示", '保存成功', 'info', function () {
              objMethod.cancel();
              role_datagrid.datagrid("reload");  // 刷新
            })
          } else {
            $.messager.alert("温馨提示", '保存失败', 'info', function () {
            })
          }
        }
      })
    },
    cancel: function () {
      role_dialog.dialog("close")
    },
    query : function () {
      var keyword = $("#keyword").textbox('getValue');
      var minHireDate = $("#minHireDate").textbox('getValue');
      var maxHireDate = $("#maxHireDate").textbox('getValue');
      var deptId = $("#deptId").textbox('getValue');
      $('#role_datagrid').datagrid('load', {
        keyword,
        minHireDate,
        maxHireDate,
        deptId
      })
    }
  }
  // 绑定事件
  $('a[data-cmd]').click(function () {
    objMethod[$(this).data('cmd')].call();
  })



})

